<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Novel;
use App\Draft;
use App\Chapter;


class DraftController extends Controller
{
    public function draftadd(Request $req, $nid){      //草稿添加
      $chapter = new Chapter();     //新建一个章节对象
      $draft = new Draft();

      $draft->nid = $nid;
      $draft->chtitle = $req->chtitle;
      $draft->content = $req->content;
      $draft->pubtime = time();
      $draft->edittime = time();
      $draft->wordcount = mb_strlen($req->content);   //草稿字数

      $draft->save();


    	// return view('published');
      return redirect("draft/$nid");
    }

    public function draftlist($nid){                         //草稿列表
      $drafts = Draft::where('nid', $nid)->orderby('drid')->get();    //取出章节信息
    	// dd($chapters);
      $novel = Novel::find($nid);   //取出小说名字
      return view('admin/draft', ['drafts'=>$drafts , 'nid'=>$nid , 'novel'=>$novel]);     //把数据传到draft页面
    }

    public function draftdel($nid,$drid){            //章节删除
      $draft = Draft::find($drid);
      $novel = Novel::find($nid);                         //用于更新小说字数       
      $draft->delete();                                    //删除章节
      return redirect("draft/$nid");
	}

	public function getDraftedit($nid,$drid){              //草稿编辑
      $draft = Draft::find($drid);
      return view('admin/draftedit' , ['draft' => $draft , 'nid' => $nid]);
    }

	public function postDraftedit(Request $req , $nid , $drid){  //草稿编辑
      $novel = Novel::find($nid);                         //用于更新小说字数 
      $chapter = new Chapter();
      
      $chapter->nid = $nid;                        
      $chapter->chtitle = $req['chtitle'];
      $chapter->content = $req['content'];
      $chapter->pubtime = time();  
      $chapter->edittime = time();
      $chapter->wordcount = mb_strlen($req['content']);       //章节字数
      
      $chapter->save();

      $draft = Draft::where('drid', $drid);                    //编辑之后删除草稿

      $novel->wordcount += $chapter->wordcount;              //再加上编辑后的章节字数
      $novel->chnum++;                                     //小说章节数加一
      $novel->edittime = $chapter->edittime;           //小说更新时间
      $novel->new = $chapter->chid;                    //更新小说最新章节
      $novel->save();                                     //更新字数后入库

      return redirect("published/$nid");
    }

}
